package com.lezhi.socialgram.service.friend.impl;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.friend.FriendMapper;
import com.lezhi.socialgram.model.friend.*;
import com.lezhi.socialgram.service.friend.FriendService;
import com.lezhi.socialgram.util.Param;
import com.lezhi.socialgram.util.Result;
import com.lezhi.socialgram.util.ResultUtils;
import com.lezhi.socialgram.util.TableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by daizhen on 2017/4/5.
 */
@Service
public class FriendServiceImpl implements FriendService {

    private static final Logger logger = LoggerFactory.getLogger(FriendServiceImpl.class);

    @Autowired
    FriendMapper friendMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public Result slide(MyLike myLike) {
        try {
            myLike.setTable(TableUtils.getTableNameWithId(MyLike.class, myLike.getUid(), 100));
            //以uid维度插入喜欢/不喜欢关系
            friendMapper.insertMyLike(myLike);
            LikeMe likeMe = new LikeMe(TableUtils.getTableNameWithId(LikeMe.class, myLike.getFid(), 100),
                    myLike.getFid(), myLike.getUid());
            //fid被看过的人计数+1
            stringRedisTemplate.opsForHash().increment(myLike.getFid() + "_info", Param.SEEN_COUNT, 1);
            if (myLike.getIsLike() == 1) {//如果喜欢，那么在对方的维度增加喜欢我的人
                friendMapper.insertLikeMe(likeMe);
                //我喜欢的人，喜欢我的人计数+1
                //uid喜欢人数
                stringRedisTemplate.opsForHash().increment(myLike.getUid() + "_info", Param.LIKE_COUNT, 1);
                //fid被喜欢人数
                stringRedisTemplate.opsForHash().increment(myLike.getFid() + "_info", Param.LIKE_ME_COUNT, 1);
                //判断对方是否已经喜欢过自己
                LikeMe likeMeByFid = friendMapper.queryLikeMeById(new LikeMe(TableUtils.getTableNameWithId(LikeMe.class, myLike.getUid(), 100),
                        myLike.getUid(), myLike.getFid()));
                if (likeMeByFid != null) {
                    //互相喜欢成为好友
                    //fid维度的好友表
                    friendMapper.insertFriend(new Friend(TableUtils.getTableNameWithId(Friend.class, myLike.getUid(), 100),
                            myLike.getUid(), myLike.getFid()));
                    //uid维度的好友表
                    friendMapper.insertFriend(new Friend(TableUtils.getTableNameWithId(Friend.class, myLike.getFid(), 100),
                            myLike.getFid(), myLike.getUid()));
                    return ResultUtils.success("friend");
                }
            }
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @Override
    public Result myLikeList(Long userId, Long lastFid, Integer operation) {
        try {
            MyLike like = new MyLike(TableUtils.getTableNameWithId(MyLike.class, userId, 100),
                    userId);
            like.setOperation(operation == null ? 1 : operation);
            like.setFid(lastFid);
            List<MyLike> myLikeList = friendMapper.queryMyLike(like);
            List<IUser> iUsers = new CopyOnWriteArrayList<>();
            for (MyLike myLike : myLikeList) {
                Long friend = myLike.getFid();
                IUser iUser = new IUser();
                iUser.setTable(TableUtils.getTableNameWithId(IUser.class, friend, 10));
                iUser.setUserId(friend);
                IUser user = friendMapper.queryUserById(iUser);
                iUsers.add(iUser);
            }
            return ResultUtils.success(iUsers);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @Override
    public Result likeMeList(Long userId, Long lastFid, Integer operation) {
        try {
            LikeMe like = new LikeMe(TableUtils.getTableNameWithId(LikeMe.class, userId, 100)
                    , userId);
            like.setOperation(operation == null ? 1 : operation);
            like.setFid(lastFid);
            List<LikeMe> likeMeList = friendMapper.queryLikeMe(like);
            List<IUser> iUsers = new CopyOnWriteArrayList<>();
            for (LikeMe likeMe : likeMeList) {
                Long friend = likeMe.getFid();
                IUser iUser = new IUser();
                iUser.setTable(TableUtils.getTableNameWithId(IUser.class, friend, 10));
                iUser.setUserId(friend);
                IUser user = friendMapper.queryUserById(iUser);
                iUsers.add(iUser);
            }
            return ResultUtils.success(iUsers);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @Override
    public Result pullIntoBlackList(Black black) {
        try {
            friendMapper.insertBlackList(black);
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @Override
    public Result myBlackList(Long userId, Long lastFid, Integer operation) {
        try {
            Black like = new Black(userId);
            like.setOperation(operation == null ? 1 : operation);
            like.setFid(lastFid);
            List<Black> blackList = friendMapper.queryMyBlackList(like);
            List<IUser> iUsers = new CopyOnWriteArrayList<>();
            for (Black black : blackList) {
                Long friend = black.getFid();
                IUser iUser = new IUser();
                iUser.setTable(TableUtils.getTableNameWithId(IUser.class, friend, 10));
                iUser.setUserId(friend);
                IUser user = friendMapper.queryUserById(iUser);
                iUsers.add(iUser);
            }
            return ResultUtils.success(iUsers);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @Override
    public Result myFriendList(Long userId, Long lastFid, Integer operation) {
        try {
            Friend like = new Friend(TableUtils.getTableNameWithId(Friend.class, userId, 100)
                    , userId);
            like.setOperation(operation == null ? 1 : operation);
            like.setFid(lastFid);
            List<Long> friendList = friendMapper.queryFriendList(like);
            List<IUser> iUsers = new CopyOnWriteArrayList<>();
            for (Long friend : friendList) {
                IUser iUser = new IUser();
                iUser.setTable(TableUtils.getTableNameWithId(IUser.class, friend, 10));
                iUser.setUserId(friend);
                IUser user = friendMapper.queryUserById(iUser);
                iUsers.add(iUser);
            }
            return ResultUtils.success(iUsers);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }
}
